package clone;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: homechen
 * Date: 2024-03-24
 * Time: 19:20
 */
class Address implements Cloneable {
    private String city;

    public Address(String city) {
        this.city = city;
    }

    public String getCity() {
        return city;
    }

    @Override
    public String toString() {
        return "Address{" +
                "city='" + city + '\'' +
                '}';
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    protected Address clone() throws CloneNotSupportedException {
        return (Address) super.clone();
    }
}

class Person implements Cloneable {
    private String name;
    private int age;
    private Address address;

    public Person(String name, int age, Address address) {
        this.name = name;
        this.age = age;
        this.address = address;
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", address=" + address +
                '}';
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    protected Person clone() throws CloneNotSupportedException {
        Person clonePerson = (Person) super.clone(); // 将当前对象克隆一份
        clonePerson.setAddress(this.address.clone());
        return clonePerson;
    }
}

public class DeepClone {
    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("北京");
        Person person1 = new Person("唐晨", 20, address);
        // 克隆对象  这里是深克隆
        Person person2 = person1.clone();
        person2.setName("晨哥");
        person2.getAddress().setCity("广西");
        person2.setAge(21);

        System.out.println(person1);
        System.out.println(person2);

    }
}
